import request from "./utils/axios"
App({
  onLaunch() {
    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        if(res.code){
          // code赋值
          this.globalData.code=res.code
        }//if
      },//success
    });//wx.login
  },//onLaunch
  // 获取sessionKey和openId
  getopenIdAndSessionKey(){
    console.log("正在获取sessionKey及openId")
      wx.request({
        url: "https://api.weixin.qq.com/sns/jscode2session?appid="+this.globalData.appId+"&secret=9f523b9dca67241d6ef3971ad0212871&js_code="+this.globalData.code+"&grant_type=authorization_code",
        success:res=>{
          // 当前时间
          var timestamp = Date.parse(new Date());
          // 加上过期期限
          var expiration = timestamp + 7199500; //缓存差不多2小时
          // 存入Storage
          this.globalData.miniOpenId=res.data.openid
          wx.setStorageSync('expiration', expiration)
          wx.setStorageSync('miniOpenId', res.data.openid);
          wx.setStorageSync('sessionKey', res.data.session_key);
        }
      })
  },  
  // 缓存是否过期
  accessTokenIsExpiration() {
    // 当前时间
    var timestamp = Date.parse(new Date());
    // 缓存中的过期时间
    var data_expiration = wx.getStorageSync("expiration");
    // 如果缓存中没有data_expiration，说明也没有token，还未登录
    if (data_expiration!=null) {
      // 如果超时了,重新获取
      if (timestamp > data_expiration) {
        wx.clearStorageSync("expiration");
        this.getopenIdAndSessionKey()
        return
      }else{
        return;
      }
    }
    this.getopenIdAndSessionKey()
  },
  // 获取用户数据
  getUserInfo(){
    request.get("/wx_user/miniLogin?miniOpenId="+wx.getStorageSync('miniOpenId')).then(res=>{
      if (res.data!=null) {
        wx.setStorageSync('UserInfo', res.data)
      }else{
        wx.setStorageSync('UserInfo', null)
      }
    })
  },
  globalData: {
    miniOpenId:"",
    userInfo: null,
    AppId:"wx7e3d219b2faf80c2",
    code:""
  }
})